﻿using System;
using System.Threading;

namespace RxjhServer
{
	public class WUserBase<TContext> : IWUser<TContext>
	{
		[NonSerialized]
		private ReaderWriterLockSlim _objLock = Locks.GetLockInstance(LockRecursionPolicy.NoRecursion);

		private string _credentials = string.Empty;

		public DateTime Timestamp
		{
			get;
			set;
		}

		public int Index
		{
			get;
			set;
		}

		public bool Invalid
		{
			get;
			set;
		}

		public TContext Context
		{
			get;
			set;
		}

		public string Credentials
		{
			get
			{
				return this._credentials;
			}
		}

		public IDisposable ReadLock
		{
			get
			{
				return new ReadOnlyLock(this._objLock);
			}
		}

		public IDisposable UpdateLock
		{
			get
			{
				return new ReadLock(this._objLock);
			}
		}

		public IDisposable WriteLock
		{
			get
			{
				return new WriteLock(this._objLock);
			}
		}

		public virtual void Reset()
		{
			this._credentials = Guid.NewGuid().ToString();
			this.Context = default(TContext);
		}

		public bool Authentication(string credentials)
		{
			return !string.IsNullOrEmpty(this._credentials) && !string.IsNullOrEmpty(credentials) && !(this._credentials != credentials);
		}

		public WUserBase()
		{
			this.Index = -1;
			this.Timestamp = DateTime.MinValue;
			this.Invalid = true;
		}

		public override string ToString()
		{
			return string.Format("{0}-{1}", this.Index, this.Timestamp);
		}
	}
}
